#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>


#define 	SLEEP 		1
#define 	CLEANUP 	909090

char* 	str;


void clean( void *arg )
{
	int p;

	p = *(int*)arg;

	printf("clean p : %d\n", p);

	//return 0;
}


void *loopPrintTID( void *arg )
{
	int 	oldstate;
	char 	str1[5];
	char 	str2[5];
	char 	str3[10];
	int 	cleanp;

	cleanp = CLEANUP;

	pthread_cleanup_push( clean, &cleanp );

	cleanp = 101010;

	printf( "thread start!\n" );

	memset( str1, 0, sizeof(str1) );
	memset( str2, 0, sizeof(str2) );
	memset( str3, 0, sizeof(str3) );

	strcpy( str1, "12" );
	strcpy( str2, "34" );
	strcpy( str3, str1 );
	strcat( str3, str2 );

	str = str3;

	printf( "str_pt : %s\n", str );

	// 状態設定  joinable detached
	pthread_detach( pthread_self() );
	// cancelの処理 PTHREAD_CANCEL_ENABLE/PTHREAD_CANCEL_DISABLE
	pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, &oldstate );
	// cancelのtiming PTHREAD_CANCEL_DEFERRED/PTHREAD_CANCEL_ASYNCHRONOUS
	pthread_setcanceltype( PTHREAD_CANCEL_DEFERRED, &oldstate );

	while( 1 ){
		//printf( "thread id is %u\n", (unsigned)pthread_self() );

		// cancel point 設定
		pthread_testcancel();

		//sleep( SLEEP );
	}

	printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

	pthread_cleanup_pop(1);

}



/*
int main( int argc, char* argv[] )
{
	pthread_t 	pt;
	int 		ret;
	int 		re,s;

	s = 1;

	printf( "thread create!\n" );
	pthread_create( &pt, NULL, loopPrintTID, NULL );
	printf( "thread create end !\n" );

	getchar();

	printf( "str1 : %s", str );

	pthread_cancel( pt );

	while( s ){
		re = pthread_kill( pt, 0 );
		if( re == ESRCH || re == EINVAL ){
			s = 0;
		}
		getchar();
	}

	printf( "str2 : %s", str );

	getchar();

}
*/

int main( int argc, char* argv[] )
{
	pthread_t 	pt;
	int 		ret;
	int 		re,s;


	while( 1 ){
		s = 1;

		printf( "thread create!\n" );
		pthread_create( &pt, NULL, loopPrintTID, NULL );
		printf( "thread create end !\n" );

		sleep( 2 );

		pthread_cancel( pt );

		while( s ){
			re = pthread_kill( pt, 0 );
			if( re == ESRCH || re == EINVAL ){
				s = 0;
			}
		}
	}
}